import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/network/business_exception.dart';
import 'package:casdon/modules/recipe/data/api/miffy_product_list_api.dart';
import 'package:casdon/modules/recipe/data/repository/recipe_repository.dart';
import 'package:casdon/modules/recipe/providers/recipe_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class MiffyProductListUsecase {
  final RecipeRepository _repository;

  const MiffyProductListUsecase(this._repository);

  Future<List<MiffyProduct>> execute() async {
    try {
      var ret = await _repository.getRecipeMiffyProducts();
      return ret ?? [];
    } on BusinessException {
      rethrow;
    } catch (e) {
      Log.e("MiffyProductListUsecase 失败", e.toString(), StackTrace.current);
      throw Exception("MiffyProductListUsecase 失败");
    }
  }
}

final miffyRecipeProductListUsecaseProvider = Provider(
  (ref) => MiffyProductListUsecase(ref.read(recipeRepository)),
);

final miffyRecipeProductListProvider = FutureProvider<List<MiffyProduct>>((
  ref,
) async {
  final useCase = ref.read(miffyRecipeProductListUsecaseProvider);
  ref.keepAlive();

  try {
    return await useCase.execute();
  } catch (e, stack) {
    debugPrint('加载产品列表失败: $e\n$stack');
    rethrow;
  }
});
